<?php

class MyFilesController extends AppController {

    function add() {
        if (!empty($this->data) &&
                is_uploaded_file($this->data['MyFile']['File']['tmp_name'])) {
            $fileData = fread(fopen($this->data['MyFile']['File']['tmp_name'], "r"), $this->data['MyFile']['File']['size']);

            $this->data['MyFile']['name'] = $this->data['MyFile']['File']['name'];
            $this->data['MyFile']['type'] = $this->data['MyFile']['File']['type'];
            $this->data['MyFile']['size'] = $this->data['MyFile']['File']['size'];
            $this->data['MyFile']['data'] = $fileData;

            $this->MyFile->save($this->data);
            $this->Session->setFlash(__('The file has been saved', true));
            $this->redirect(array('controller' => 'clients', 'action' => 'view/'.$this->data['MyFile']['client_id']));
        }
        $clients = $this->MyFile->Client->find('list');
        $this->set(compact('clients'));
    }

    function download($id) {
        Configure::write('debug', 0);
        $file = $this->MyFile->findById($id);
        header('Content-type: ' . $file['MyFile']['type']);
        header('Content-length: ' . $file['MyFile']['size']); // some people reported problems with this line (see the comments), commenting out this line helped in those cases
        header('Content-Disposition: attachment; filename="' . $file['MyFile']['name'] . '"');
        echo $file['MyFile']['data'];
        exit();
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for File', true));
            $this->redirect($this->referer());
        }
        if ($this->MyFile->delete($id)) {
            $this->Session->setFlash(__('File deleted', true));
            $this->redirect($this->referer());
        }
        $this->Session->setFlash(__('File was not deleted', true));
        $this->redirect($this->referer());
    }

}

?>